// pages/Tabbar/Home/Home.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getBrandConfig , queryAppInforMation , getUserPushMessage , getGradeConfig , queryGoodsCloseConfig } from '../../../api/brand';
import { queryGoodsListTab , queryGoodsCityConfig , queryGoodsCommonConfig , getGoodsCouponInfo } from '../../../api/goods';
import { getAddress , getUser , queryGoodsFreeFreightMark } from '../../../api/user';
import { queryGoodsPurchaseRecord } from '../../../api/order';
const regeneratorRuntime = require('../../../common/runtime');
import { formatTime } from '../../../utils/util';
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    assetsAddress: assetsAddress,
    navBgColor: 'none',
    bannerList: [],
    showTabNav: false,
    tabNavTop: app.globalData.CustomBar,
    soltMarginRight: app.globalData.soltMarginRight,
    screenWidth: wx.getSystemInfoSync().screenWidth,
    message: '欢迎来到我爱花！',
    isShowBackTop: false,
    classData: [], // 特殊分类-和当前分类列表数据
    seckillList: {
      data: []
    }, // 秒杀列表数据
    homeGoodsMaxNumByCate: 8, // 查询商品的数量
    homeGoodsLineItemWidth: 0, // 每行最多多少个商品
    province: '上海市',
    city: '上海市',
    country: '浦东新区',
    storehouseId: '',
    couponAmount: 0, // 注册优惠券金额
    isShowCouponPop: false,
    discount: 100, // 等级权益折扣
    name: '',
    isReachStandard: false, // 免运费是否达标
    recordTotal: 0, // 疯抢人数
    recordList: [], // 疯抢人员列表
    goodsList: [], // 商品列表
    closeStartTime: '', // 打烊开始时间
    closeEndTime: '', // 打烊结束时间
    showCloseTime: false, // 是否展示打烊时间
    showPrivacyAuthor: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
    });
    var _this = this;
    if (wx.onNeedPrivacyAuthorization){
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }  
    
    // this._getGoods();
    console.log(wx.getStorageSync('pathName'),'patgName');
    console.log(wx.getStorageSync('params'),'params');
    if(wx.getStorageSync('params') != '' && wx.getStorageSync('pathName') == 'goodsDetail'){
      wx.navigateTo({
        url: `/pages/Goods/GoodDetail/GoodDetail?item=${wx.getStorageSync('params')}`,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onPageScroll (e) { 
    // console.log(e,'页面滚动')
    if(e.scrollTop > 150 && this.data.navBgColor != 'white'){
      this.setData({
        navBgColor: 'white',
        showTabNav: true,
        isShowBackTop: true,
      })
    }else if(e.scrollTop < 150 && this.data.navBgColor == 'white'){
      this.setData({
        navBgColor: 'none',
        showTabNav: false,
        isShowBackTop: false,
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var stCountry = wx.getStorageSync('country');
    // if(this.data.country != stCountry && stCountry){
    //   this.setData({
    //     province: wx.getStorageSync('province'),
    //     city: wx.getStorageSync('city'),
    //     country: stCountry,
    //   })
    //   this._getBrandConfig();
    // }else{
    //   this.getUserAddress();
    // }
    this.getUserAddress();
    this._getGoodsCouponInfo1();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getMes();
    this._getBrandConfig();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取版本配置信息
  _getBrandConfig(){
    let _this = this;
    getBrandConfig({isGroup: '1'})
    .then(async res => {
      if(res.success){
        if(res.data.length > 0){
          _this.setData({
            homeGoodsMaxNumByCate: parseInt(res.data[0].homeGoodsMaxNumByCate),
            homeGoodsLineItemWidth: wx.getSystemInfoSync().screenWidth / parseInt(res.data[0].homeGoodsMaxNumByLine),
          })
          // console.log(_this.data.homeGoodsMaxNumByLine,'homeGoodsMaxNumByLine')
        }
        try {
          var grade = await _this._getUser();
          var gradeList = await _this._getGradeConfig();
          var discount = 100;
          for (let index = 0; index < gradeList.length; index++) {
            const item = gradeList[index];
            if(Number(item.rebateDescription) < discount){
              discount = Number(item.rebateDescription);
            }
            // if(item.grade == grade){
            //   discount = item.rebateDescription;
            // }
          }
          _this.setData({
            discount: discount,
          })
          _this._queryGoodsCityConfig();
        } catch (error) {
          wx.showToast({
            title: error,
            icon: 'none',
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取轮播图信息
  getNewsList() {
    let _this = this
    queryAppInforMation({infoType: 1,storehouseId: _this.data.storehouseId})
      .then(res => {
        if (res.success) {
          _this.setData({
            bannerList: res.data.content
          })
        } else {
          wx.showToast({
            title: res.errMessage,
            icon: 'none'
          })
        }
      })
  },
  // 获取消息推送
  getMes(){
    let _this = this;
    queryAppInforMation({infoType: 5,storehouseId: _this.data.storehouseId})
    .then(res => {
      if (res.success) {
        _this.setData({
          message: res.data.content[0].content,
        })
      } else {
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
    // getUserPushMessage({})
    // .then(res => {
    //   if(res.success){
    //     if(res.data.content.length > 0){
    //       _this.setData({
    //         message: res.data.content.message,
    //       })
    //     }
    //   }else{
    //     wx.showToast({
    //       title: res.errMessage,
    //       icon: 'none',
    //     })
    //   }
    // })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  scrollTo(e){
    let name = e.target.dataset.name||e.currentTarget.dataset.name;
    name = '#' + name;
    var tity = wx.createSelectorQuery();
    tity.select(name).boundingClientRect();
    tity.selectViewport().scrollOffset();
    tity.exec(res => {
      console.log(res[0].top);
      console.log(res[1].scrollTop)
      wx.pageScrollTo({
        duration: 0,
        scrollTop: res[0].top + res[1].scrollTop - 140,
      })
    })
  },
  // 获取商品城市配置（仓库）
  _queryGoodsCityConfig(){
    let _this = this;
    var {province , city , country} = _this.data;
    queryGoodsCityConfig({province: province,city: city,area: country})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            storehouseId: res.data.content[0].storehouseId,
          })
          wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
          wx.setStorageSync('storehouseName', res.data.content[0].storehouseName)
          _this._queryGoodsArea();
          _this.getAllData();
        }else{
          queryGoodsCityConfig({province: province,city: city,})
          .then(res => {
            if(res.success){
              if(res.data.content.length > 0){
                _this.setData({
                  storehouseId: res.data.content[0].storehouseId,
                })
                wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
                _this._queryGoodsArea();
                _this.getAllData();
              }else{
                queryGoodsCityConfig({province: province,})
                .then(res => {
                  if(res.success){
                    if(res.data.content.length > 0){
                      _this.setData({
                        storehouseId: res.data.content[0].storehouseId,
                      })
                      wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
                      _this._queryGoodsArea();
                      _this.getAllData();
                    }else{
                      queryGoodsCityConfig({})
                      .then(res => {
                        if(res.success){
                          if(res.data.content.length > 0){
                            _this.setData({
                              storehouseId: res.data.content[0].storehouseId,
                            })
                            wx.setStorageSync('storehouseId', res.data.content[0].storehouseId)
                            _this._queryGoodsArea();
                            _this.getAllData();
                          }else{
                            wx.showToast({
                              title: '当前地区暂无仓库配置',
                              icon: 'none',
                            })
                          }
                        }else{
                          wx.showToast({
                            title: res.errMessage,
                            icon: 'none'
                          })
                        }
                      })
                    }
                  }else{
                    wx.showToast({
                      title: res.errMessage,
                      icon: 'none'
                    })
                  }
                })
              }
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none'
              })
            }
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品分区信息
  _queryGoodsArea(){
    let _this = this;
    queryGoodsCommonConfig({type: '1'})
    .then(async res => {
      if(res.success){
        if(res.data.content.length > 0){
          var arr = [];
          var seckillList = [];
          for(let i = 0; i < res.data.content.length; i++){
            let cate = res.data.content[i];
            let cateData = await _this._getGoodsInfo(cate.id);
            cate.data = cateData;
            if(cate.name != '秒杀区' && cate.name != '商品区'){
              arr.push(cate);
            }else if(cate.name == '秒杀区'){
              seckillList = cate;
            }else{
              wx.setStorageSync('areaId', cate.id)
            }
          }
          console.log(seckillList,'seckillList')
          console.log(arr,'classData')
          _this.setData({
            classData: arr,
            seckillList: seckillList,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品列表信息
  _getGoodsInfo(areaId){
    let _this = this;
    return new Promise((resolve,reject) => {
      queryGoodsListTab({size:_this.data.homeGoodsMaxNumByCate,areaId: areaId,storehouseId: _this.data.storehouseId,goodsName: _this.data.name})
      .then(res => {
        if(res.success){
          var arr = [];
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            item.sellingPrices = (item.sellingPrice * _this.data.discount / 100).toFixed(2);
            item.disDiffTime = 0;
            if(item.areaId == 201){
              var nowDate = new Date().getTime();
              var disStartDate = new Date(item.discountStartTime.replace(/-/g, "/")).getTime();
              item.disDiffTime = (disStartDate - nowDate);
              console.log(item.disDiffTime,'打折开始剩余时间')
            }
            arr.push(item);
          }
          resolve(arr);
        }else{
          resolve([]);
        }
      })
    })
  },
  // 定位
  async getUserAddress(){
    var _this = this;
    try {
      var arr = await _this._getAddress();
      console.log(arr,'地址arr')
      if(arr.length > 0){
        _this._getBrandConfig();
        return;
      }
      wx.getSetting({
        success: (res) => {
          console.log(res,'res')
          if(res.authSetting['scope.userLocation']){
            _this._getFuzzy();
          }else{
            wx.authorize({
              scope: 'scope.userLocation',
              success: ()=>{
                _this._getFuzzy();
              },
              fail: (err) => {
                console.log(err,'err')
                wx.showModal({
                  title: '获取定位信息',
                  content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                  success: (res) => {
                    if(res.confirm){
                      wx.openSetting({
                        success: (res) => {
                          if(res.authSetting['scope.userLocation']){
                            _this._getFuzzy();
                          }
                        },
                      })
                    }else{
                      _this._getBrandConfig();
                    }
                  }
                })
              }
            })
          }
        }
      })
    } catch (error) {
      
    }
  },
  // 获取用户收货地址
  _getAddress(){
    let _this = this;
    return new Promise((resolve,reject) => {
      getAddress({})
      .then(res => {
        if(res.success){
          if(res.data.length > 0){
            var address = res.data[0];
            for (let index = 0; index < res.data.length; index++) {
              const item = res.data[index];
              if(item.isDefault == '1'){
                address = item;
              }
            }
            _this.setData({
              province: address.province,
              city: address.city,
              country: address.area,
            })
            resolve(res.data)
          }else{
            resolve([])
          }
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 进入页面模糊定位
  _getFuzzy(){
    let _this = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res,'位置信息')
        const latitude = res.latitude
        const longitude = res.longitude
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude,
          },
          success: (res) => {
            console.log(res,'res')
            res = res.result;
            _this.setData({
              province: res.address_component.province,
              city: res.address_component.city,
              country: res.address_component.district,
            })
            wx.setStorageSync('province', res.address_component.province);
            wx.setStorageSync('city', res.address_component.city);
            wx.setStorageSync('country', res.address_component.district);
            _this._getBrandConfig();
          },
          fail: (err) => {
            console.log(err,'err')
          }
        })
      },
      fail: (err) => {
        console.log(err,'err')
        _this._getBrandConfig();
      }  
    })
  },
  // 获取用户优惠券信息
  _getGoodsCouponInfo(){
    let _this = this;
    var startTime = formatTime(new Date(new Date().getTime() - 60000),'Y-M-D h:m:s');
    var endTime = formatTime(new Date(),'Y-M-D h:m:s')
    getGoodsCouponInfo({status: '0',type: '0',startTime: startTime,endTime: endTime})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            isShowCouponPop : true
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  _getGoodsCouponInfo1(){
    let _this = this;
    getGoodsCouponInfo({status: '0',type: '0',})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            couponAmount : res.data.content[0].amount
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 关闭优惠券弹框
  closeCouponPop(){
    this.setData({
      isShowCouponPop: false,
    })
  },
  // 获取用户信息
  _getUser(){
    return new Promise((resolve,reject) => {
      getUser().then(res => {
        if(res.success){
          resolve(res.data.grade);
        }else{
          reject(res.errMessage);
        }
      })
    })
  },
  // 获取品牌等级配置
  _getGradeConfig(){
    return new Promise((resolve,reject) => {
      getGradeConfig()
      .then(res => {
        if(res.success){
          resolve(res.data.content);
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 输入框发生变化
  onSearchChange(e) {
    this.setData({
      name: e.detail,
    });
  },
  // 输入框搜索
  onSearch(){
    this._queryGoodsArea();
  },
  noEve(){},
  // 查询用户是否免运费
  _queryGoodsFreeFreightMark(){
    let _this = this;
    queryGoodsFreeFreightMark({storehouseId: _this.data.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          isReachStandard: res.data.isFreeFreight,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  showDesc(e){
    let name = e.target.dataset.name||e.currentTarget.dataset.name;
    queryAppInforMation({infoType: '2',title: name,page: 0})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          var itm = res.data.content[0];
          // if(res.data.content[0].imgUrl){
          //   wx.navigateTo({
          //     url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(itm.imgUrl)}&title=${JSON.stringify(item.label)}`,
          //   })
          // }else if(res.data.content[0].content){
          //   wx.navigateTo({
          //     url: `/pages/Link/LinkText/LinkText?content=${JSON.stringify(item.content)}&title=${JSON.stringify(item.label)}`,
          //   })
          // }
          wx.showModal({
            showCancel: false,
            title: name,
            content: itm.content,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 展示免运费规则
  mianyunfeiguize(){
    let _this = this;
    queryAppInforMation({infoType: '15',title: '打包费及运输费规则',page: _this.data.page})
      .then(res => {
        if(res.success){
          if(res.data.content.length > 0){
            var item = res.data.content[0];
            wx.navigateTo({
              url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(item.imgUrl)}&title=${JSON.stringify(item.title)}`,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  // 搜索栏
  searchGoods(){
    wx.switchTab({
      url: '/pages/Tabbar/Classification/Classification',
    })
  },
  // 查询商品购买记录（包含假数据）
  _queryGoodsPurchaseRecord(){
    let _this = this;
    queryGoodsPurchaseRecord({storehouseId: _this.data.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          recordList: res.data.content,
          recordTotal: res.data.totalElements,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品列表信息
  _getGoods(){
    let _this = this;
    var storehouseId = wx.getStorageSync('storehouseId');
    queryGoodsListTab({size: 20,storehouseId: storehouseId,areaId: '0'})
    .then(res => {
      if(res.success){
        _this.setData({
          goodsList: res.data.content,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  toLink(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item)
    if(item.jumpUrl != '' && item.jumpUrl != null && item.jumpUrl.substring(0,4) == 'http'){
      wx.navigateTo({
        url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(item.jumpUrl)}&title=${JSON.stringify(item.title)}`,
      })
    }
  },
  // 获取商店打烊时间
  _queryGoodsCloseConfig(){
    let _this = this;
    queryGoodsCloseConfig({storehouseId: _this.data.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          closeStartTime: res.data.content.length > 0 ? res.data.content[0].startTime.substring(0,5) : '',
          closeEndTime: res.data.content.length > 0 ? res.data.content[0].endTime.substring(0,5) : '',
        })
        if(_this.data.closeStartTime != '' && _this.data.closeEndTime != ''){
          var nowH = new Date().getHours();
          var nowM = new Date().getMilliseconds();
          var nowTime = new Date().getTime();
          // 判断打烊时间是否跨天
          var startH = parseInt(_this.data.closeStartTime.substring(0,2));
          var endH = parseInt(_this.data.closeEndTime.substring(0,2));
          var startT = new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} ${_this.data.closeStartTime}`).getTime();
          var endT = new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} ${_this.data.closeEndTime}`).getTime();
          console.log(nowH,'nowH');
          console.log(startH,'startH');
          console.log(endH,'endH');
            console.log(startT,'startT')
            console.log(endT,'endT')
          if(startH > endH){
            // 跨天，开始时间大于结束时间
            if(nowTime < endT || nowTime > startT){
              _this.setData({
                showCloseTime: true,
              })
            }
          }else{
            if(nowTime > startT && nowTime < endT){
              _this.setData({
                showCloseTime: true,
              })
            }
          }
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
    this.getUserAddress();
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
  },
  getAllData(){
    this.getNewsList();
    // this._getBrandConfig();
    this.getMes();
    this._getGoodsCouponInfo();
    this._queryGoodsPurchaseRecord();
    this._queryGoodsCloseConfig();
    this._queryGoodsFreeFreightMark();
    this._getGoods();
  },
  // 折扣商品打折时间开始
  finished(){
    this._queryGoodsArea();
  },
  // 跳转商品详情
  goDetail(e){
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item,'item');
    if(item.areaId == 201 && item.disDiffTime > 0){
      wx.showToast({
        title: '商品暂未开始售卖...',
        icon: 'none',
      });
      return;
    }
    wx.navigateTo({
      url: `${url}?item=${JSON.stringify(item)}&cateParentName=${JSON.stringify('')}&cateName=${JSON.stringify(item.goodsName)}`,
    })
  }
})